package org.example.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.example.utils.ThreadLocalUtil;

import java.util.Map;

/*拦截器对象*/
@Component//加载到spring容器中
public class LoginInterceptor implements HandlerInterceptor {

    //请求来是执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截请求 做令牌验证
        String token = request.getHeader("Authorization");
        //if(request.getHeader("H1").equals("123")){return true;}
        System.out.println("token的值--->"+token);
        //解析token
        try {
            if (token==null) {
                //token不存在
                response.setStatus(401);
                return false;
            }
            //不正确token会报错
            Map<String, Object> stringtoken = JwtUtil.parseToken(token);
            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(stringtoken);
            //放行请求
            return true;
        } catch (Exception e) {
            //设置http响应状态码
            response.setStatus(401);
            return false;//不放行代码
        }
    }

    //请求结束后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
